package com.futurelight.recipes.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.futurelight.recipes.R;
import com.futurelight.recipes.model.ExtendedIngredient;
import com.futurelight.recipes.model.Result;

import java.util.ArrayList;
import java.util.List;

public class IngredientAdapter extends RecyclerView.Adapter<IngredientAdapter.MyViewHolder> {

    private List<ExtendedIngredient> extendedIngredients = new ArrayList<>();

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater from = LayoutInflater.from(parent.getContext());
        View inflate = from.inflate(R.layout.item_ingredient, parent, false);
        return new MyViewHolder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.setIngredients(extendedIngredients.get(position));
    }

    @Override
    public int getItemCount() {
        if (extendedIngredients == null){
            return 0;
        }
        return extendedIngredients.size();
    }

    public void setIngerdients(List<ExtendedIngredient> extendedIngredients) {
        this.extendedIngredients = extendedIngredients;
        notifyDataSetChanged();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        private ExtendedIngredient extendedIngredient;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
        }
        public void setIngredients(ExtendedIngredient extendedIngredient){
            this.extendedIngredient = extendedIngredient;
            TextView name = itemView.findViewById(R.id.name);
            TextView amount = itemView.findViewById(R.id.amount);
            ImageView imageView = itemView.findViewById(R.id.ingredient_image);
            name.setText(extendedIngredient.name);
            amount.setText(extendedIngredient.amount +"\n"+ extendedIngredient.unit);
            Glide.with(itemView)
                    .load("https://spoonacular.com/cdn/ingredients_250x250/" + extendedIngredient.image)
                    .error(R.drawable.plate)
                    .into(imageView);
        }
    }
}
